const path = require('path')
const { smart } = require('webpack-merge')
const base = require('./webpack.common.js')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin')
const ImageminPlugin = require('imagemin-webpack-plugin').default
const ExtractTextPlugin = require('extract-text-webpack-plugin')

module.exports = smart(base, {
  mode: 'production',
  devtool: 'none',
  output: {
    filename: 'js/[name].[contenthash:8].js',
    path: path.resolve(__dirname, 'dist')// 输出文件的路径
  },
  module: {
    rules: [
      {
        test: /\.less$/,
        exclude: /node_modules/,
        // use: ['vue-style-loader', 'css-loader', 'less-loader']
        use: ExtractTextPlugin.extract({
          fallback: 'vue-style-loader',
          use: ['css-loader', 'less-loader']
        })
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        // use: ['vue-style-loader', 'css-loader']
        use: ExtractTextPlugin.extract({
          fallback: 'vue-style-loader',
          use: 'css-loader'
        })
      },
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
      url: 'assets/',
      title: 'luohao webpack homework',
      template: './public/index.html',
      filename: 'index.html'
    }),
    new ExtractTextPlugin({
      filename: 'css/[name].[md5:contenthash:hex:8].css',
      allChunks: true
    }),
    new CleanWebpackPlugin(),
    new CopyPlugin({
      patterns: [
        { from: 'src/assets', to: 'assets' },
        {
          from: path.resolve(__dirname, './public/favicon.ico'),
          to: path.resolve(__dirname, './dist/assets/')
        }
      ]
    }),
    new ImageminPlugin({
      test: /\.(jpe?g|png|gif|svg|ico)$/i,
      pngquant: {
        quality: '95-100'
      }
    })
  ],
  optimization: {
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: {
            // 删除所有的 `console` 语句，可以兼容ie浏览器
            drop_console: true,
            // 内嵌定义了但是只用到一次的变量
            collapse_vars: true,
            // 提取出出现多次但是没有定义成变量去引用的静态值
            reduce_vars: true
          },
          output: {
            // 最紧凑的输出
            beautify: false,
            // 删除所有的注释
            comments: false
          }
        }
      }),
      new OptimizeCSSAssetsPlugin({
        cssProcessorOptions: {
          safe: true
        }
      })
    ],
    splitChunks: {
      chunks: 'all'
    }
  }
})
